import { useState } from "react";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { Upload } from "antd";
import type { UploadChangeParam } from "antd/es/upload";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";
import { uploadUrl } from "../../utils/tools";
import { dalImg } from "../../utils/tools";
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

//从swipelist中通过props解构出两个参数()后面的表示是ts类型
const UploadImg = ({
  imageUrl,
  setImageUrl,
}: {
  imageUrl: string;
  setImageUrl: any;
}) => {
  //图片上传的状态
  const [loading, setLoading] = useState(false);
  // const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    //正在上传
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      // getBase64(info.file.originFileObj as RcFile, () => {
      setLoading(false);
      console.log(info.file.response); // 输出一下服务器端返回的数据
      setImageUrl(info.file.response.data);
      //});
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );
  //console.log(dalImg(imageUrl));
  return (
    <>
      <Upload
        // name 表示服务器端接收到的数据的属性名，这个参数可以从接口文档找到
        name="file"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        //action是上传图片的路径
        action={uploadUrl}
        onChange={handleChange}
      >
        {/* {imageUrl ? (
          <img src={dalImg(imageUrl)} alt="avatar" style={{ width: "100%" }} />
        ) : (
          uploadButton
        )} */}
        {imageUrl ? (
          <img src={dalImg(imageUrl)} alt="avatar" style={{ width: "100%" }} />
        ) : (
          uploadButton
        )}
      </Upload>
    </>
  );
};

export default UploadImg;
